<!-- SKU详情 - 综合表单页面 -->
<template>
  <div class="page-container">
    <el-form ref="form" class="flex_cell flex_col over_auto" :model="form" :rules="rules" v-loading="loading"
      label-position="right" label-width="140px">
      <el-form-item :label="$tt('label_message_title',)" prop="title">
        <ex_super_input v-model="form.title" />
      </el-form-item>
      <el-form-item :label="$tt('label_message_type',)" prop="msgType">
        <ex_radio_group_auto v-model="form.msgType" enum="OmsBaseNotifyMsgTypeEnum" />
      </el-form-item>
      <el-form-item :label="$tt('label_receive_message_customer',)" prop="customerIds" v-if="form.msgType == 'APPOINT'">
        <common_customer_choose :value="customerIdList" multiple @input="e => form.customerIds = e.join(',')" />
      </el-form-item>

      <el-form-item prop="content" :label="$tt('label_message_content',)" class=" flex_cell">
        <template v-slot:label><span style="width:125px">{{ $tt('label_message_content') }}</span></template>
        <div class="flex_cell editoer_content" :style="{ border: editoer_border }">
          <div :id="'toolbar_'+editorId" ><!-- 工具栏 --></div>
          <div :id="editorId" class="editor_main">
          </div>
        </div>

      </el-form-item>
    </el-form>
    <div style="padding-left: 140px ;padding-top: 10px;">
      <el-button type="primary" @click="submit">{{ $t('label_save') }}</el-button>
      <el-button @click="return_page_back">{{ $tt('label_cancel') }}</el-button>
    </div>

  </div>
</template>
<script>

let default_obj = {
  title: null,//	string 	标题
  status: "DRAFT",
  msgType: 'APPOINT',//		OmsBaseNotifyMsgTypeEnum 	消息类型: PUBLICITY 公开, APPOINT 非公开
  content: null,//	string 	内容
  customerIds: "",//		string 	内容
}
import router_params from '@/mixin/router_params';
import role_system_mixin from '@/mixin/role_system_mixin';


export default {
  mixins: [router_params, role_system_mixin],
  components: {},

  data() {
    return {
      loading: false,
      editorId: ("editor_" + Math.random()).replace(".", ""),

      editoer_border: "1px solid " + this.$globalCss.borderColor,

      form: _.cloneDeep(default_obj),
      rules: {
        customerIds: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur', label: 'label_receive_message_customer' },
        title: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur', label: 'label_message_title' },
        msgType: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur', label: 'label_message_type' },
        content: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur', label: 'label_message_content' },

      },

      editor: null,
    };
  },

  computed: {
    customerIdList() {
      return this.form.customerIds ? this.form.customerIds.split(",").filter(it => it) : [];
    },
  },
  mounted() {
    const { createEditor, createToolbar } = window.wangEditor

    const editorConfig = {
      placeholder: this.$t("tip_please_input"),
      MENU_CONF: {
        'uploadImage': {
          server: '/ums-api/resource/ResourceRpc/upload.json',
          maxFileSize: 1 * 1024 * 1024, // 1M
          maxNumberOfFiles: 10,
          // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
          allowedFileTypes: ['image/*'],
          timeout: 30 * 1000, // 5 秒
          base64LimitSize: 5 * 1024, // 5kb
          customInsert: (res, insertFn) => {                  // JS 语法
            // res 即服务端的返回结果
            if (res.code != 0) {
              this.$message.error(res.message || "上传失败")
            } else {
              insertFn(this.$ex_default_download_url + res.data.filePath, null, null)
            }
            // 从 res 中找到 url alt href ，然后插入图片
          },
        }
      },
      onChange: (editor) => {
        const html = editor.getHtml()
        this.form.content = html
        // 也可以同步到 <textarea>
      },
      onFocus: (editor) => {
        this.editoer_border = "1px solid " + this.$globalCss.primaryColor
      },
      onBlur: (editor) => {
        this.editoer_border = "1px solid " + this.$globalCss.borderColor
      },
    }

    this.$nextTick(() => {
      const editor = createEditor({
        selector: '#' + this.editorId,
        html: '',
        config: editorConfig,
        mode: 'default', // or 'simple'
      })
      this.editor = Object.seal(editor)
      const toolbarConfig = {
        excludeKeys: [
          // "codeBlock",
        ]

      }

      const toolbar = createToolbar({
        editor,
        selector: '#toolbar_' + this.editorId,
        config: toolbarConfig,
        mode: 'default', // or 'simple'
      })
      // console.log(toolbar.getConfig().toolbarKeys)
    })
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {


    init_data_default(into_params) {
      this.form = _.cloneDeep(default_obj)
      if (into_params.id) {
        this.loading = true
        this.$ajax({
          url: "/oms-api/base/OmsBaseNotifyRpc/detail.json",
          method: 'post',
          data: { id: into_params.id },
          success: (res) => {
            if (!res.data) return this.$message.error(this.$tt("label_data_loss"))
            this.form = Object.assign({},default_obj,res.data)
            this.$nextTick(()=>{
              this.editor.setHtml(this.form.content)
            })
            this.fixTabLabel()
          },
          complete: () => {
            this.loading = false
          }
        })
      } else {
      }
      this.fixTabLabel()
    },
    fixTabLabel() {
      if (!!this.form.id) {
        this.$emit("tagModifyLabel", { _key: 'label_name_code', name: this.$tt('label_edit_message'), code: this.form.title || "" })

      } else {
        this.$emit("tagModifyLabel", "label_new_message")
      }
    },

    submit() {
      this.$formRulesValidate({
        formRef: this.$refs['form'],
        rules: this.rules,
        success: () => {

          if (this.form.msgType == "PUBLICITY") {
            this.form.customerIds = ""
          }
          this.form.status = "DRAFT"
          // const skuUrl = this.form.skuUrlArr[0] && this.form.skuUrlArr[0].filePath
          this.$ajax({
            url: "/oms-api/base/OmsBaseNotifyRpc/saveUpdate.json",
            method: 'post',
            type: 'json',
            loading: true,
            data: this.form,
            success: (res) => {
              this.$message.success(this.$tt('tip_submit_success'))
              this.return_emit(null, "reload")
              this.return_page_back()
            }
          })
        }
      })

    },
  }
};

</script>
<style>
@import '../../../../common/wangeditor.css';

.editoer_content {
  border-radius: 4px;
  padding: 2px;
  z-index: 99;
}
.editor_main{
  height: 300px;
}
</style>
